﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using MediaDataModel;
using MediaService.Contract.DataEnum;
using MediaService.Contract.DataContract;
using System.Xml;
using System.IO;
using MediaDataModel.Common.Other;


namespace MediaService.ServiceContract
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public partial class MediaService:IMediaService
    {
        public MediaService()
        {
            
        }

        #region private methods

        private bool  IsUserOnline(string userId)
        {
            //Getlanguage(currentLanguage);
            bool online = false;
            lock (lockLoginObject)
            {
                if (usrStatusDic.ContainsKey(userId) == true)
                    online = usrStatusDic[userId].First().Value;
            }
            return online;
        }

        private void Initialize()
        {
            Logger.InitLogger();
        }

        #endregion

        #region public methods

        #region login

        public LoginStatus Login(string userID, string Password)
        {
            
            LoginStatus currentLogin = LoginStatus.LogInSuccess;
            using (CCTV6Entities db = new CCTV6Entities())
            {
                User loginUser = db.Users.Where(user => user.ID == userID).SingleOrDefault();
                if (loginUser == null)
                    currentLogin = LoginStatus.LogInUserNotFound;
                else if (loginUser != null)
                {
                    if (IsUserOnline(userID) == true)
                        currentLogin = LoginStatus.LogInUserAlreadyOnline;
                    else if (loginUser.Password != CommonUtility.Utility.MD5Encrypt(Password))
                        currentLogin = LoginStatus.LogInWrongPassword;
                    else if (loginUser.IsActive == false)
                        currentLogin = LoginStatus.LogInUserNotActive;

                }
            }
            return currentLogin;
        }

        public void Logout(string userID)
        {
        }

        #endregion

        #region get Disc Barcode

        public string GetDiscBarcode()
        {
            string discBarcode = null;
            try
            {
                lock (lockBarcodeObject)
                {
                    using (CCTV6Entities db = new CCTV6Entities())
                    {
                        Customer systemOwner = db.Customers.Where(customer => customer.IsOwner.Value == true).SingleOrDefault();
                        if (systemOwner != null && string.IsNullOrEmpty(systemOwner.WaterMarkerNumber) == false && systemOwner.WaterMarkerNumber.Length >= 3)
                        {
                            string currentDate = DateTime.Now.ToString("yyyMMdd");
                            var discs = db.BlueDiscs.Where(item => item.CreateDate == currentDate).OrderByDescending(item => item.Barcode);
                            if (discs != null)
                            {
                                var lastDisc = discs.FirstOrDefault();
                                if (lastDisc != null && string.IsNullOrEmpty(lastDisc.Barcode) == false)
                                    discBarcode = systemOwner.WaterMarkerNumber.Substring(0, 3) + currentDate + (short.Parse(lastDisc.Barcode.Substring(11)) + 1).ToString("00");

                                else
                                    discBarcode = systemOwner.WaterMarkerNumber.Substring(0, 3) + currentDate + "01";
                            }
                        }
                        else
                            discBarcode = "001" + DateTime.Now.ToString("yyyyMMdd") + "00";

                    }
                }

            }
            catch (Exception myE)
            {
                Logger.Write("there throws an exception when getting stored disc Barcode: " + myE.InnerException == null ? myE.Message : myE.InnerException.Message);
            }
            return discBarcode;
        }


        #endregion

        #region get Media file path on disc

        public List<MediaFile> GetMediaPackFiles(Int64 mediaPackID)
        {
            List<MediaFile> mediaPackFileList = null;
            return mediaPackFileList;
        }
        #endregion

        #region operate offline shelf

        public OperateMessage PositionOfflineShelf(string shelfSeriesNumber, short rowIndex, short columnIndex, ServiceMessage Operator)
        {
            OperateMessage operateShelf = new OperateMessage{ Result = OperateResult.Success, Message="定位成功！"};
            try
            {
                using(CCTV6Entities db = new CCTV6Entities())
                {
                    var shelf = db.OfflineShelves.Where(item => item.SeriesNumber == shelfSeriesNumber).SingleOrDefault();
                    if (shelf != null)
                    {
                        SZHardware.SZControl control = new SZHardware.SZControl();
                        string SZType = shelf.ShelfType == null ? "SZ1536" : shelf.ShelfType;  //SZ1536
                        short Port = shelf.Port.Value;      //1
                        string CDId = shelf.ShelfIndex.Value.ToString("00") + "1" + rowIndex.ToString("00") + columnIndex.ToString("000");// "01101001";
                        if (control.SendInfo(ref SZType, ref Port, ref CDId) != 7718)
                            operateShelf.Message = "定位失败，无效的离线柜命令。";
                    }
                    else
                    {
                        operateShelf.Message = "离线柜的序列号有误。";
                        operateShelf.Result = OperateResult.Failure;
                    }
                }
                
            }
            catch (Exception myE)
            {
                operateShelf.Result = OperateResult.Failure;
                operateShelf.Message = "定位失败。失败的详细信息：" + (myE.InnerException == null? myE.Message:myE.InnerException.Message);
            }
            return operateShelf;
        }
        #endregion

        #endregion
    }
}
